<?php
class BuyUnitField extends FormField {
	protected $force_price = false;
	/**
	 * @var UnitField
	 */
	protected $unitField = null;
	
	/**
	 * @var PriceField
	 */
	protected $priceField = null;
	
	/**
	 * @var TotalField
	 */
	protected $totalField = null;
	
	/**
	 * @var FeePercentageField
	 */
	protected $feePercentageField = null;
	
	/**
	 * @var FeeField
	 */
	protected $feeField = null;
	
	/**
	 * @var PayableField
	 */
	protected $payableField = null;
	
	public function __construct($name, $unit = '', $price = '', $fee_percentage = ''){
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
        Requirements::javascript('trading/javascript/BuyUnitField.js');
		$prefix = Config::inst()->get('TradeCurrency', 'currency_symbol');
		
		$this->unitField = TextField::create($name . '[unit]', _t('BuyUnitField.UNIT', 'Unit'))->addExtraClass('buy-unit')->addExtraClass('integer')->setAttribute('data-inputmask-allowminus', 'false');
		$this->priceField = TextField::create($name . '[price]', _t('BuyUnitField.BUYING_PRICE', 'Buying Price'))->addExtraClass('buy-price');
		$this->totalField = TextField::create($name . '[total]', _t('BuyUnitField.TOTAL', 'Total'))->addExtraClass('buy-total')->setReadonly(true)->setAttribute('tabindex', '-1')->setAttribute('data-prefix', $prefix);
		$this->feePercentageField = HiddenField::create($name . '[fee_percentage]', '')->addExtraClass('buy-fee-percentage');
		$this->feeField = TextField::create($name . '[fee]', _t('BuyUnitField.FEE', 'Fee'))->addExtraClass('buy-fee')->setReadonly(true)->setAttribute('tabindex', '-1')->setAttribute('data-prefix', $prefix);
		$this->payableField = TextField::create($name . '[payable]', _t('BuyUnitField.PAYBLE', 'Payble'))->addExtraClass('buy-payable')->setReadonly(true)->setAttribute('tabindex', '-1')->setAttribute('data-prefix', $prefix);
		
		$value = array(
			'unit' => $unit,
			'price' => $price,
			'fee_percentage' => $fee_percentage
		);
		
		parent::__construct($name, '', $value);
	}
	
	public function FieldHolder($properties = array()) {
		if($this->getForcePrice()){
			$this->priceField->setReadonly(true);
		}
		if($this->feePercentageField->Value() > 0){
			$this->feeField->setDescription(_t('BuyUnitField.CHARGE_PROCESSING_FEE', 'Chargable processing fee {percentage} of total amount', '', array('percentage' => DBField::create_field('Percentage', $this->feePercentageField->Value())->Nice())));
		}
		if($this->Required()){
			$this->unitField->setAttribute('required', 'required');
			$this->unitField->setAttribute('aria-required', 'true');
			$this->priceField->setAttribute('required', 'required');
			$this->priceField->setAttribute('aria-required', 'true');
		}
        return sprintf('<div class="field buyunit">%s %s %s %s %s %s</div>', $this->unitField->FieldHolder(), $this->priceField->FieldHolder(), $this->totalField->FieldHolder(), $this->feePercentageField->FieldHolder(), $this->feeField->FieldHolder(), $this->payableField->FieldHolder());
	}

	public function Field($properties = array()) {
		return $this->FieldHolder($properties);
	}
	
	public function setForcePrice($bool){
		$this->force_price = $bool;
		return $this;
	}
	
	public function getForcePrice(){
		return $this->force_price;
	}
	
	public function setUnit($unit){
		$this->value['unit'] = $unit;
		return $this;
	}
	
	public function getUnit(){
		return $this->value['unit'];
	}
	
	public function setPrice($price){
		$this->value['price'] = $price;
		return $this;
	}
	
	public function getPrice(){
		return $this->value['price'];
	}
	
	public function setFeePercentage($fee_percentage){
		$this->value['fee_percentage'] = $fee_percentage;
		return $this;
	}
	
	public function getFeePercentage(){
		return $this->value['fee_percentage'];
	}
	
	/**
	 * Set the field value.
	 * 
	 * @param mixed $value
	 * @return FormField Self reference
	 */
	public function setValue($value) {
		if(is_array($value)) {
			$this->value = array(
				'unit' => $value['unit'],
				'price' => $value['price'],
				'fee_percentage' => $value['fee_percentage']
			);
		} else {
			$this->value = array(
				'unit' => $this->getUnitValue(),
				'price' => $this->getPriceValue(),
				'fee_percentage' => $this->getFeePercentage()
			);
		}
		
		$this->value['unit'] = (is_numeric($this->value['unit'])) ? $this->value['unit'] : 0;
		$this->value['price'] = (is_numeric($this->value['price'])) ? $this->value['price'] : 0;
		$this->value['fee_percentage'] = (is_numeric($this->value['fee_percentage'])) ? $this->value['fee_percentage'] : 0;

		$total = $this->value['unit'] * $this->value['price'];
		$this->unitField->setValue($this->value['unit']);
		$this->priceField->setValue($this->value['price']);
		$this->totalField->setValue(DBField::create_field('TradeCurrency', $total)->Nice());
		$this->feePercentageField->setValue($this->value['fee_percentage']);
		$this->feeField->setValue(DBField::create_field('TradeCurrency', $total * $this->value['fee_percentage'])->Nice());
		$this->payableField->setValue(DBField::create_field('TradeCurrency', $total * (1 + $this->value['fee_percentage']))->Nice());
		
		return $this;
	}
	
	public function setDisabled($bool) {
		parent::setDisabled($bool);
		$this->unitField->setDisabled($bool);
		$this->priceField->setDisabled($bool);
		$this->totalField->setDisabled($bool);
		$this->feeField->setDisabled($bool);
		$this->payableField->setDisabled($bool);
		return $this;
	}

	public function setReadonly($bool) {
		parent::setReadonly($bool);
		$this->unitField->setReadonly($bool);
		$this->priceField->setReadonly($bool);
		return $this;
	}

	/**
	 * Returns a readonly version of this field
	 */
	public function performReadonlyTransformation() {
		$this->unitField = $this->unitField->performReadonlyTransformation();
		$this->priceField = $this->priceField->performReadonlyTransformation();
		$this->totalField = $this->totalField->performReadonlyTransformation();
		$this->feeField = $this->feeField->performReadonlyTransformation();
		$this->payableField = $this->payableField->performReadonlyTransformation();

		$this->setReadonly(true);
		return $this;
	}
	
	/**
	 * Return a disabled version of this field.
	 * Tries to find a class of the class name of this field suffixed with "_Disabled",
	 * failing that, finds a method {@link setDisabled()}.
	 *
	 * @return FormField
	 */
	public function performDisabledTransformation() {
		$this->unitField = $this->unitField->performDisabledTransformation();
		$this->priceField = $this->priceField->performDisabledTransformation();
		$this->totalField = $this->totalField->performDisabledTransformation();
		$this->feeField = $this->feeField->performDisabledTransformation();
		$this->payableField = $this->payableField->performDisabledTransformation();
		
		$this->setDisabled(true);
		return $this;
	}
	
	/**
	 * Method to save this form field into the given data object.
	 * By default, makes use of $this->dataValue()
	 * 
	 * @param DataObjectInterface $record DataObject to save data into
	 */
	public function saveInto(DataObjectInterface $record) {
		$var = $this->dataValue();
		$record->setCastedField($this->getName(), $var);
		$record->setCastedField('Unit', $var['unit']);
		$record->setCastedField('Price', $var['price']);
		$record->setCastedField('FeePercentage', $var['fee_percentage']);
		$total = $var['unit'] * $var['price'];
		$record->setCastedField('Total', $total);
		$record->setCastedField('Fee', $total * $var['fee_percentage']);
		$record->setCastedField('Payable', $total * (1 + $var['fee_percentage']));
	}
	
	function setError($message, $messageType) {
		$this->unitField->setError($message, $messageType);
		return $this;
	}
	
    function validate($validator) {
    	$var = $this->Value();
        if($var['unit'] <= 0) {
        	$validator->validationError(
            	$this->getName(), 
            	_t('BuyUnitField.INVALID_UNIT', 'Trade unit is invalid'), 
            	'warning'
			);
            return false;
        }
		
		if($var['price'] <= 0) {
        	$validator->validationError(
            	$this->getName(), 
            	_t('BuyUnitField.INVALID_PRICE', 'Trade price is invalid'), 
            	'warning'
			);
            return false;
        }
		
		if($var['fee_percentage'] < 0) {
        	$validator->validationError(
            	$this->getName(), 
            	_t('BuyUnitField.INVALID_FEE_PERCENTAGE', 'Fee percentage is invalid'), 
            	'warning'
			);
            return false;
        }

        return true;
    }
}
?>
